$(document).ready(function(){

///////////////////// TOGGLE CLASS ACTIVE ON CLICK AN MENU ITEM // ///////////
	
	// /// REGISTER EVENTS ////
	$("select#encounter_room").change(function() {
		viewEncounterQueue($('select#encounter_room option:selected').val()); 		
	});
	
	$("select#doctor_room").change(function() {
		viewDoctorQueue(); 		
	});		
	
	$('div.documentListHeader').click(function() {
		$(this).next().toggle();
	});
	
	
});	

function remove(t){
	var ticketItemId	=	t.id;
	$.ajax({
		type:	"GET",
		url:	"../Queue/RemoveInProgressTicketItem?set_ajax_view",
		data:	"ticketItemId=" + ticketItemId,
		dataType:	"json",
		beforeSend:	function(){
			$('div#reload').hide();
			$('div#innerLoading').show();
		},
		success:	function(data){
			viewDoctorQueue();
		}
	});
}

function reloadEncounterQueue() {
	viewEncounterQueue($('select#encounter_room option:selected').val()); 	
}

/**
 * View an encounter queue
 * roomId = all 	: all rooms
 * roomId = int	: specified room
 */
function viewEncounterQueue(roomId) {		
	var inlineTable = $('table#table_inline_encounter_queue');	
	var inprogressTable = $('table#table_inprogress_encounter_queue');
	var waitingTable = $('table#table_waiting_encounter_queue');
	
	$.ajax({
			type:		"GET",
			url:		"../Queue/RenderEncounterQueueAjax?set_ajax_view",
			data:		"room_id=" + roomId,
			dataType:   "json",		
			beforeSend: function() {
				$('div#reload').hide();
				$('div#innerLoading').show();
			},
			complete: function() {
				$('div#reload').show();
				$('div#innerLoading').hide();
			},									
			success: 	function(data) {																			
				fillTableData(inlineTable, data.in_line.body);
				fillTableData(inprogressTable, data.in_progress.body);
				fillTableData(waitingTable, data.in_waiting.body);
				
				fillTotalTableData($('div#inline_encounter_queue'), data.in_line.total_table);
				fillTotalTableData($('div#inprogress_encounter_queue'), data.in_progress.total_table);
				fillTotalTableData($('div#waiting_encounter_queue'), data.in_waiting.total_table);																				
				
				triggerUpdate(inlineTable, inprogressTable, waitingTable);
			}
		});
}

function triggerUpdate(inlineTable, inprogressTable, waitingTable) {		
	inlineTable.trigger('update');	
	inprogressTable.trigger('update');
	waitingTable.trigger('update');		
}

function viewDoctorQueue() {	
	var roomId = $('select#doctor_room option:selected').val();
	
	var inlineTable = $('table#table_inline_encounter_queue');	
	var inprogressTable = $('table#table_inprogress_encounter_queue');
	var waitingTable = $('table#table_waiting_encounter_queue');
	
	$.ajax({
			type:		"GET",
			url:		"../Queue/RenderDoctorQueueAjax?set_ajax_view",
			data:		"room_id=" + roomId,		
			dataType:   "json",				
			beforeSend: function() {
				$('div#reload').hide();
				$('div#innerLoading').show();
			},
			complete: function() {
				$('div#reload').show();
				$('div#innerLoading').hide();				
			},									
			success: 	function(data) {																			
				fillTableData(inlineTable, data.in_line.body);
				fillTableData(inprogressTable, data.in_progress.body);
				fillTableData(waitingTable, data.in_waiting.body);
				
				fillTotalTableData($('div#inline_encounter_queue'), data.in_line.total_table);
				fillTotalTableData($('div#inprogress_encounter_queue'), data.in_progress.total_table);
				fillTotalTableData($('div#waiting_encounter_queue'), data.in_waiting.total_table);	
				
				triggerUpdate(inlineTable, inprogressTable, waitingTable);	
				
				$('table#table_inprogress_encounter_queue tr.contextMenu').contextMenu('doctorQueueMenu',{
					bindings: {
	    				'remove': remove,
	    				'changeDoctor':	changeDoctor
	    				}
				});

				// add context menu to 'waiting' queue -- ntmdung
				$('table#table_waiting_encounter_queue tr.contextMenu').contextMenu('doctorQueueMenu',{
					bindings: {
	    				'remove': remove,
	    				'changeDoctor':	changeDoctor
	    				}
				});
				}
		});
}

function changeDoctor(t) {
	ticketItemId	=	t.id;
	$.ajax({
		type:	"GET",
		url:	"../Queue/ChangeDoctor?set_ajax_view",
		data: 	'ticketItemId=' + ticketItemId,
		dataType: "json",
		beforeSend: function() {
			$('div#reload').hide();
			$('div#innerLoading').show();
		},
		complete: function() {
			$('div#reload').show();
			$('div#innerLoading').hide();
		},
		success: function(data) {
			if (data.available == false) {
				//button close
				var buttons = {};
				buttons[_('Close')] = function() {
						$(this).dialog('close');		
					};
				generalDialog(null,null,_('Current status is <span class="impression">{0}</span>. Please select another patient.',data.result),'warn',{
						autoOpen: true,			
						bgiframe: true,
						resizable: true,
						modal: true,							
						buttons: buttons
					});
				viewDoctorQueue();				
			} else {
				var message	=	'';
				message	+=	'<div><p>' + _("Select Doctor/Technician:") + ' </p>' + data.result+"</div>";
				message	+=	"<div style='padding-top: 10px;'><fieldset><legend>" + _("Change in medicial profile") + "</legend>";
				message	+=	"<input id='changePrescription' type='checkbox'/><label for='changePrescription'>" + _("Prescription") + "</label></fieldset></div>";
				promptConfirm('',message,
						function(o,v) {
							submitChangeDoctor(ticketItemId, v.find('#doctorList :selected').val(), 
							v.find('#changePrescription').is(':checked'));
							return true;
						},'SelectCancel','',_('Cancel'));				
				
			}			
		}
	});
}

// modify submitChangeDoctor(..) prototype -- ntmdung
// function submitChangeDoctor(ticketItemId, doctorId, changeRefraction, changePrescription) {
function submitChangeDoctor(ticketItemId, doctorId, changePrescription) {
	$.ajax({
		type:	"GET",
		url:	"../Queue/SubmitChangeDoctor?set_ajax_view",
		data:	"ticketItemId=" + ticketItemId +
				"&doctorId=" + doctorId+
				"&changePrescription=" + changePrescription,
		beforeSend: function() {
			$('div#reload').hide();
			$('div#innerLoading').show();
		},
		complete: function() {
			$('div#reload').show();
			$('div#innerLoading').hide();
		},
		success: function() {
			viewDoctorQueue();
		}		
	});
}

function viewCashierQueue() {
	var cashierTable = $('table#table_inline_encounter_queue');	
	var inprogressTable = $('table#table_inprogress_encounter_queue');	
	
	$.ajax({
			type:		"GET",
			url:		"../Queue/RenderCashierQueueAjax?set_ajax_view",			
			dataType:   "json",						
			beforeSend: function() {
				$('div#reload').hide();
				$('div#innerLoading').show();
			},
			complete: function() {
				$('div#reload').show();
				$('div#innerLoading').hide();				
			},							
			success: 	function(data) {																			
				fillTableData(cashierTable, data.cashier.body);
				fillTableData(inprogressTable, data.in_progress.body);
				fillTotalTableData($('div#inline_encounter_queue'), data.cashier.total_table);
				fillTotalTableData($('div#inprogress_encounter_queue'), data.in_progress.total_table);								
				
				cashierTable.trigger('update');
				inprogressTable.trigger('update');											
			}
		});
}

function fillTotalTableData(parentDiv, data) {
	$('table.total_table', parentDiv).remove();
	parentDiv.append(data);
	parentDiv.children('table:last-child').addClass('total_table');
}

function fillTableData(table, data) {
	$('tbody', table).children().remove();	
	$('tbody', table).append(data);
	table.find('tr:last-child').addClass('last');
		
	if ($('tbody tr', table).length > 0) {
		table.show();
	} else {
		table.hide();
	}	
}


function showTransferMessage(roomName, purpose) {
	var message = _('Please go to <span id="next_place">{0}</span> for <span id="purpose">{1}<span>', roomName,purpose);
	$('span#next_place').css({"color":"red", "font-size":"medium"});
	$('span#purpose').css("color", "red");
	// no button
	generalDialog(null,null,message);
}

/**
 * Check whether a ticket item is in OPEN status
 * IF YES redirect to the URL
 *    NO  alert user, refresh queue
 */
function preCheckOpening(ticketItemId, url) {
	$.ajax({
		url: "PreCheckOpeningAjax?set_ajax_view",
		data: "ticket_item_id=" + ticketItemId,
		dataType: "json",
		success: function(data) {
			if (data.available) {
				window.location = url;
			} else {	
				var message = _('Current status is <span class="impression">{0}</span><p>Please select another patient</p>', data.status);				
				// no button
				generalDialog(null,null,message); 
				viewDoctorQueue();
			}
		}
	});		
}

/**
 * Check whether a ticket item is in WAITING status
 * IF YES redirect to the URL
 *    NO  alert user, refresh queue
 */
function preCheckWaiting(ticketItemId, url) {
	$.ajax({
		url: "PreCheckWaitingAjax?set_ajax_view",
		data: "ticket_item_id=" + ticketItemId,
		dataType: "json",
		success: function(data) {
			if (data.available) {
				window.location = url;
			} else {	
				var message = _('Current status is <span class="impression">{0}</span><p>Please select another patient</p>', data.status);				
				// no button
				generalDialog(null,null,message); 
				viewDoctorQueue();
			}
		}
	});		
}

/**
 * Check whether a ticket item is CASHIER QUEUE 
 * IF YES redirect to the URL
 *    NO  alert user, refresh queue
 */
function preCheckAvailable(ticketItemId, url) {
	$.ajax({
		url: "PreCheckAvailableAjax?set_ajax_view",
		data: "ticket_item_id=" + ticketItemId,
		dataType: "json",
		success: function(data) {
			if (data.available) {
				window.location = url;
			} else {	
				var message = _('Current status is <span class="impression">{0}</span><p>Please select another patient</p>', data.status);				
				// button close
				var buttons = {};
				buttons[_('Close')] = function() {
						$(this).dialog('close');		
					};
				generalDialog(null,null,message,null,{
						autoOpen: true,			
						bgiframe: true,
						resizable: true,
						modal: true,							
						buttons: buttons
					});
				viewCashierQueue();
			}
		}
	});		
}